import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useThemeConfig, LAYOUT_TYPES } from '../contexts/ThemeConfigContext';
import { routeConfig } from '../config/routes';
import AuthGuard from '../components/AuthGuard';
import MainLayout from './MainLayout';
import TopMenuLayout from './TopMenuLayout';
import MixedLayout from './MixedLayout';

const LayoutSelector = ({ children }) => {
  const location = useLocation();
  const { layoutType, isLayoutChanging } = useThemeConfig();
  const [displayLayoutType, setDisplayLayoutType] = useState(layoutType);
  const [animationPhase, setAnimationPhase] = useState('idle'); // idle, fadeOut, fadeIn

  // 检查当前路径是否需要布局
  const needsLayout = () => {
    // 标准化路径 - 移除尾随斜杠进行比较
    const normalizedPath = location.pathname.replace(/\/$/, '') || '/';
    const currentRoute = routeConfig.find(route => route.path === normalizedPath);

    // 不需要布局的页面类型：
    // 1. 登录相关页面
    // 2. 路由配置中明确标记 requireAuth = false 的页面
    // 3. 错误页面等独立页面
    const noLayoutPaths = ['/login', '/register', '/forgot-password', '/404', '/500'];

    // 检查标准化路径是否在无布局路径列表中
    if (noLayoutPaths.includes(normalizedPath)) {
      return false;
    }

    // 如果路由配置中明确标记不需要认证，也不使用布局
    if (currentRoute?.meta?.requireAuth === false) {
      return false;
    }

    return true;
  };

  useEffect(() => {
    if (isLayoutChanging) {
      // 直接切换布局，不使用动画
      setDisplayLayoutType(layoutType);
      setAnimationPhase('idle');
    }
  }, [isLayoutChanging, layoutType]);

  const getLayoutComponent = (type) => {
    switch (type) {
      case LAYOUT_TYPES.TOPBAR:
        return <TopMenuLayout>{children}</TopMenuLayout>;
      case LAYOUT_TYPES.MIXED:
        return <MixedLayout>{children}</MixedLayout>;
      case LAYOUT_TYPES.SIDEBAR:
      default:
        return <MainLayout>{children}</MainLayout>;
    }
  };

  const getAnimationClass = () => {
    if (animationPhase === 'fadeOut') return 'layout-changing-out';
    if (animationPhase === 'fadeIn') return 'layout-changing-in';
    return '';
  };

  // 如果当前页面不需要布局，直接渲染内容
  if (!needsLayout()) {
    return children;
  }

  return (
    <AuthGuard>
      <div className={getAnimationClass()} style={{ height: '100vh', overflow: 'hidden' }}>
        {getLayoutComponent(displayLayoutType)}
      </div>
    </AuthGuard>
  );
};

export default LayoutSelector;
